package com.tangshuai;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2024-07-23 10:57
 */
public class Test2 {
    /**
     * itextpdf 通过html转pdf
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String htmlTemplate = filePathToStr("D:\\index.html");
        // 默认加载系统所有字体，设置默认字体为微软雅黑
        // 字体需要生效的话，需要安装ttf或otf结尾的字体，ttc结尾的不生效，而且需要为所有用户安装
        DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, true, "Microsoft YaHei");
        ConverterProperties converterProperties = new ConverterProperties();
        converterProperties.setFontProvider(defaultFontProvider);
        // 加载中文字体, 创建一个输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HtmlConverter.convertToPdf(htmlTemplate, bos, converterProperties);
        OutputStream outputStream = new FileOutputStream("D:\\output1.pdf"); // 初始化 outputStream
        bos.writeTo(outputStream);
    }

    public static String filePathToStr(String filePath) {
        try {
            // 读取文件内容并返回
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
            return null;
        }
    }
}
